var AV = require('leanengine');
var async = require('async');
require('date-utils');
var cartCtrl =require('./cart.js');
//商品收藏的模型信息
var ActivitySignDayGive = AV.Object.extend("ActivitySignDayGive");
var UserCoupon = AV.Object.extend('UserCoupon');
var Coupons = AV.Object.extend('Coupons');
var User = AV.Object.extend('_User');
var PointFlow = AV.Object.extend('PointFlow');
var AmountFlow = AV.Object.extend('AmountFlow');
//ActivitySignDayUser
var SignDayUserM = AV.Object.extend('ActivitySignDayUser');
var querySignDayUser = new AV.Query(SignDayUserM);
//ActivitySignDayDetail
var SignDayDetailM = AV.Object.extend('ActivitySignDayDetail');
var querySignDayDetail = new AV.Query(SignDayDetailM);
//ActivitySignDayGive
var SignDayGiveM = AV.Object.extend('ActivitySignDayGive');
var querySignDayGive = new AV.Query(SignDayGiveM);
//ActivitySignDayRule
var SignDayGiveRuleM = AV.Object.extend('ActivitySignDayRule');
var querySignDayGiveRule = new AV.Query(SignDayGiveRuleM);

var ActivitySignDayDetail = AV.Object.extend('ActivitySignDayDetail');

module.exports = {
    //签到赠送优惠券直接领取优惠券
    setSignDayGiftGiveYouHuiJuan:function(uid,objectId,cid){
        var timestamp = Date.parse(new Date());
        if(objectId&&uid){
            var promise = new AV.Promise();
            async.waterfall([
                function(callback){
                    query = new AV.Query(ActivitySignDayGive);
                    query.get(objectId).then(function(res){
                        if(res.get('Uid')==uid){
                            if(res.get('GiveMold')==0){
                                res.set("GiveMold",1);
                                res.set("GiveTime",new Date());
                                res.save();
                                callback(null,cid);
                            }else{
                                callback({code:1052,msg:"本月优惠券已领取"});
                            }
                        }else{
                            callback({code:1045,msg:"objectId与uid不匹配"});
                        }
                    }).catch(function(err){
                        callback({code:1046,msg:"objectId记录不存在"});
                    });
                },
                //判断优惠券是否存在
                function(cid,callback){
                    query = new AV.Query(Coupons);
                    query.equalTo("batchNo",cid);
                    query.first().then(function(res){
                        if(res){
                            callback(null,res);
                        }else{
                            callback({code:1047,msg:"优惠券未设置"});
                        }
                    });
                },
                //领取优惠券
                function(res,callback){
                    var takeCoupon = new UserCoupon();
                    var endVaildTime=String(timestamp+7*3600*24*1000);
                    var newCoupon={'uid':uid,'cid':res.get("batchNo"),GiveTime:new Date(),'validityEndPeriod':endVaildTime,'used':0,'status':1,coupon:res.attributes};
                    takeCoupon.save(newCoupon).then(function(res){
                        callback(null,{code:0,msg:"领取成功",res:res});
                    });
                }
            ],function(err,result){
                if(err){
                    promise.reject(err);
                }else{
                    promise.resolve(result);
                }
            });
            return promise;
        }else{
            if(!uid){
                return new AV.Promise.error({code:1044,msg:'uid为空'});
            }else if(!cid){
                return new AV.Promise.error({code:1048,msg:'优惠券编号为空'});
            }else{
                return new AV.Promise.error({code:1000,msg:'objectId为空'});
            }
        }
    },
    //签到赠积分
    setSignDayGiftGiveJiFeng:function (uid,objectId) {
        if(uid&&objectId){
            var promise = new AV.Promise();
            async.waterfall([
                //判断->是否存在->是否领取
                function(callback){
                    query = new AV.Query(ActivitySignDayGive);
                    query.get(objectId).then(function(res){
                        if(res.get('Uid')==uid){
                            if(res.get('GiveMold')==0){
                                res.set("GiveMold",1);
                                res.set("GiveTime",new Date());
                                res.save();
                                callback(null,uid);
                            }else{
                                callback({code:1049,msg:"本月已领取积分奖励"});
                            }
                        }else{
                            callback({code:1045,msg:"objectId与uid不匹配"});
                        }
                    }).catch(function(err){
                        callback({code:1046,msg:"objectId记录不存在"});
                    });
                },
                //获取用户信息
                function(uid,callback){
                    query = new AV.Query(User);
                    query.get(uid).then(function(res){
                        var beforepoint=res.get('point');
                        res.increment('point',200);
                        res.save();
                        callback(null,uid,200,beforepoint);
                    }).catch(function(err){
                        callback({code:1050,msg:"uid用户不存在",err:err});
                    });
                },
                //记录积分流水
                function(uid,point,beforepoint,callback){
                    pointFlow = new PointFlow();
                    pointFlow.save({
                        content: "连续签到三天奖励积分+200",
                        userid: uid,
                        newpoint: point,
                        beforepoint: beforepoint,
                        afterpoint: beforepoint+point
                    }, {
                        success: function(pointflow) {
                            callback(null,{code:0,msg:"领取积分奖励成功"});
                        },
                        error: function(pointflow, error) {
                            callback(null,{code:0,msg:"领取积分奖励成功,流水记录失败！"});
                        }
                    });
                },
            ],function(err,result){
                if(err){
                    promise.reject(err);
                }else{
                    promise.resolve(result);
                }
            });
            return promise;
        }else{
            if(!uid){
                return new AV.Promise.error({code:1044,msg:'uid为空'});
            }else{
                return new AV.Promise.error({code:1000,msg:'objectId为空'});
            }
        }
    },
    //签到赠余额
    setSignDayGiftGiveYuE:function (uid,objectId) {
        if(uid&&objectId){
            var promise = new AV.Promise();
            //console.log(uid);
            async.waterfall([
                //判断->是否存在->是否领取
                function(callback){
                    query = new AV.Query(ActivitySignDayGive);
                    query.get(objectId).then(function(res){
                        if(res.get('Uid')==uid){
                            if(res.get('GiveMold')==0){
                                res.set("GiveMold",1);
                                res.save();
                                callback(null,res.get('RuleDays'))
                            }else{
                                callback({code:1051,msg:"余额奖励已领取"});
                            }
                        }else{
                            callback({code:1045,msg:"objectId与uid不匹配"});
                        }
                    }).catch(function(err){
                        callback({code:1046,msg:"objectId记录不存在"});
                    });
                },
                //获
                function(rule,callback){
                    if(rule=="D365"){
                        query = new AV.Query(ActivitySignDayGive);
                        var arr=['D365','D90','D180'];
                        arr.forEach(function(data,i){
                            query = new AV.Query(ActivitySignDayGive);
                            query.equalTo('Uid',uid);
                            query.equalTo('RuleDays',arr[i]);
                            query.equalTo('AllSignEnable',true);
                            query.first().then(function(result){
                                if(result) {
                                    result.set('AllSignEnable', false);
                                    result.set('GiveTime', new Date());
                                    result.save().then(function () {
                                        if (i == 2) {
                                            callback(null, 2000);
                                        }
                                    }).catch(function (err) {
                                        callback({code: 9999, msg: err});
                                    });
                                }else{
                                    callback({code:1045,msg:'objectId与uid不匹配'})
                                }
                            });
                        });
                    }else if(rule=="D180"){
                        callback(null,500);
                    }
                },
                //获取用户信息开始充值
                function(amount,callback){
                    query = new AV.Query(User);
                    query.get(uid).then(function(res){
                        var beforeamount=res.get('amount');
                        res.increment('amount',amount);
                        res.save().then(function(obj){
                            callback(null,amount,beforeamount);
                        });
                    }).catch(function(err){
                        callback({code:1050,msg:"uid用户不存在"});
                    });
                },
                //记录下充值流水
                function(amount,beforeamount,callback){
                    var amountFlow =new AmountFlow();
                    var days=180;
                    if(amount===2000){
                        days=365;
                    }
                    amountFlow.save({
                        content: "连续签到"+days+"天奖励现金充值+"+amount+"元",
                        userid:uid,
                        newamount: amount,
                        beforeamount: beforeamount,
                        afteramount:beforeamount+amount
                    }, {
                        success: function(post) {
                            callback(null,amount);
                        },
                        error: function(post, error) {
                            callback(null,amount);
                        }
                    });
                },
                function(amount,callback){
                    if(amount==2000){
                        query = new AV.Query(SignDayUserM);
                        query.equalTo('Uid',uid);
                        query.first().then(function(res){
                            res.set('AllSignDay',0);
                            res.save().then(function(){
                                callback(null,{code:0,msg:"2000元余额奖励成功"});
                            });
                        });
                    }else{
                        callback(null,{code:0,msg:"500元余额奖励成功"});
                    }

                }
            ],function(err,result){
                if(err){
                    promise.reject(err);
                }else{
                    promise.resolve(result);
                }
            });
            return promise;
        }else{
            if(!uid){
                return new AV.Promise.error({code:1044,msg:'uid为空'});
            }else{
                return new AV.Promise.error({code:1000,msg:'objectId为空'});
            }
        }
    },
    getSignDayValue:function(userid){
        var promise = new AV.Promise();
        if(userid){
            async.waterfall([
                function(callback){
                    var query = new AV.Query(SignDayUserM);
                    query.equalTo('Uid',userid);
                    query.first().then(function(userInfo){
                        if(!userInfo || userInfo.length<1 || userInfo === "undefined"){
                            //没有任何签到记录，则直接返回一个值
                            return callback({code:1003,msg:'没有签到记录',MonthSignDay:0,AllSignDay:0,SignState:0});
                        }
                        //判断日期，当前日期与前一天的时间差是否为1天，如果是则显示正常数据。如果不是，则清空表内数据，返回连续签到天数为0
                        var year = userInfo.get('Year');
                        var month = userInfo.get('Month');
                        var day = userInfo.get('Day');
                        var lastTime = new Date(year+'-'+month+'-'+day+' 00:00:00'); //.toFormat('YYYY-MM-DD 00:00:00');
                        var now = new Date().toFormat('YYYY-MM-DD 00:00:00');
                        now=new Date(now);
                        //now-lastTime==1天
                        var isOneDay = Math.floor((now - lastTime)/(24*3600*1000));
                        callback(null, isOneDay,userInfo);
                    }).catch(function(err){
                        callback({code:9999,reason:err});
                    });
                    //callback(null, {code:1,msg:'success'});
                },
                function(isOneDay,userInfo,callback){
                    if(isOneDay > 1){
                        userInfo.set('MonthSignDay',0);
                        userInfo.set('AllSignDay',0);
                        userInfo.save().then(function(){
                            callback(null, {code:0,msg:'',MonthSignDay:0,AllSignDay:0,SignState:0});
                        }).catch(function(err){
                            callback({code:9999,reason:err});
                        });
                    }else if(isOneDay === 1){
                        //获取MonthSignDay和AllSignDay
                        var MonthSignDay = userInfo.get('MonthSignDay');
                        var AllSignDay = userInfo.get('AllSignDay');
                        callback(null, {code:0,msg:'',MonthSignDay:MonthSignDay,AllSignDay:AllSignDay,SignState:0});
                    }else{
                        var MonthSignDay = userInfo.get('MonthSignDay');
                        var AllSignDay = userInfo.get('AllSignDay');
                        callback(null, {code:0,msg:'',MonthSignDay:MonthSignDay,AllSignDay:AllSignDay,SignState:1});
                    }
                }
            ],function(err,result){
                if(err){
                    promise.reject(err);
                }else{
                    promise.resolve(result);
                }
            });
            return promise;
        }else{
            return new AV.Promise.error("userid should not be empty!");
        }
    },
    /**
     * 签到操作1	Myron	setSginDayAction	!userid:String	code:int,msg:string
     * 说明：1、先判断ActivitySignDayUser表中是否存在信息
     *      2、如果存在：则进入第3步
     *         如果不存在：则插入一条记录，连续签到天数变为1，同时向ActivitySignDayDetail插入一条数据
     *      3、判断日期和当前是否相差一天
     *          3.1、如果是：
     *              3.1.1、判断是否为同一个月
     *                  如果是：则表示连续签到，连续签到增加1，同时向ActivitySignDayDetail插入一条数据
     *                  如果不是：则将MonthSignDay设为0，AllSignDay增加1，同时向ActivitySignDayDetail插入一条数据
     *          3.2、如果不是：清空记录（连续签到天数设置为0）
     * @param userid
     */
    setSignDayAction:function(userid){
        var promise = new AV.Promise();
        if(userid){
            async.auto({
                getGiftRule:function(callback){
                    var query1 = new AV.Query(SignDayGiveRuleM);
                    //console.log('======getGiftRule=====');
                    query1.find().then(function(ruleInfo){
                        if(!ruleInfo || ruleInfo.length < 1){
                            return callback({code:1002,reason:'请先维护rule表'});
                        }
                        var ruleJson={};
                        async.eachSeries(ruleInfo,function(eachInfo,callback1){
                            ruleJson[eachInfo.get('Day')]= eachInfo;
                            callback1(null, ruleJson);
                        },callback(null,ruleJson));
                    }).catch(function(err){
                        callback({code:9998,reason:err});
                    });
                },
                //1、先判断ActivitySignDayUser表中是否存在信息
                hasUser:function(callback){
                    var query = new AV.Query(SignDayUserM);
                    query.equalTo('Uid',userid);
                    query.first().then(function(userInfo){
                        callback(null, userInfo);
                    }).catch(function(err){
                        callback({code:9997,reason:err});
                    });
                },
                updateUser:['hasUser',function(callback,results){
                    //不存在任何签到记录，则插入一条新记录。结束整个程序
                    var userInfo =results.hasUser;
                    //console.log('======updateUser start=====');
                    //console.log(userInfo);
                    var newMonthSignDay = 0;
                    var newAllSignDay = 0;
                    if(!userInfo || userInfo.length<1){
                        var now = new Date();
                        var addNewUser = new SignDayUserM();
                        addNewUser.set('Uid',userid);
                        addNewUser.set('MonthSignDay',1);
                        addNewUser.set('AllSignDay',1);
                        addNewUser.set('Day',parseInt(now.getDate()));
                        addNewUser.set('Month',parseInt(now.getMonth()+1));
                        addNewUser.set('Year',parseInt(now.getFullYear()));
                        newMonthSignDay = 1 ;
                        newAllSignDay = 1 ;
                        addNewUser.save().then(function(){
                            //console.log('======updateUser end1=====');
                            callback(null, {Day:now.getDate(),Month:now.getMonth()+1,Year:now.getFullYear(),MonthSignDay:newMonthSignDay,AllSignDay:newAllSignDay});
                        }).catch(function(err){
                            callback({code:9996,reason:err});
                        });
                    }else{
                        var MonthSignDay = userInfo.get('MonthSignDay');
                        var AllSignDay = userInfo.get('AllSignDay');
                        var year = userInfo.get('Year');
                        var month = userInfo.get('Month');
                        var day = userInfo.get('Day');
                        var lastTime = new Date(year+'-'+month+'-'+day+' 00:00:00');
                        var now = new Date().toFormat('YYYY-MM-DD 00:00:00');
                        now=new Date(now);
                        //now-lastTime==1天
                        var isOneDay = Math.floor((now - lastTime)/(24*3600*1000));
                        if(isOneDay < 1){
                            //console.log('======updateUser end=====');
                            return callback({code:1001,reason:'已签过到'});
                        }
                        if(isOneDay === 1){
                            //判断是否为同一个月
                            if(month != now.getMonth()+1){
                                newMonthSignDay=1;
                            }else{
                                newMonthSignDay = MonthSignDay+1;
                            }
                            newAllSignDay = AllSignDay+1;
                        }else if(isOneDay > 1){
                            newMonthSignDay=1;
                            newAllSignDay = 1;
                        }
                        userInfo.set('MonthSignDay',newMonthSignDay);
                        userInfo.set('AllSignDay',newAllSignDay);
                        userInfo.set('Day',now.getDate());
                        userInfo.set('Month',(now.getMonth()+1));
                        userInfo.set('Year',now.getFullYear());
                        userInfo.save().then(function(){
                            //console.log('======updateUser end2=====');
                            callback(null, {Day:now.getDate(),Month:now.getMonth()+1,Year:now.getFullYear(),MonthSignDay:newMonthSignDay,AllSignDay:newAllSignDay});
                        }).catch(function(err){
                            callback({code:9995,reason:err});
                        });
                    }
                }],
                hasDetail:function(callback){
                    //向签到详情表中添加
                    var query = new AV.Query(SignDayDetailM);
                    query.equalTo('Uid',userid);
                    //console.log('======hasDetail=====');
                    query.first().then(function(detail){
                        callback(null, detail);
                    }).catch(function(err){
                        callback({code:9994,reason:err});
                    });
                },
                updateDetail:['hasDetail','updateUser',function(callback,results){
                    var detail = results.hasDetail;
                    var date = results.updateUser;
                    //console.log('======updateDetail start=====');
                    if(!detail || detail.length<1 || detail === 'undefined'){
                        var addNewDetail = new SignDayDetailM();
                        addNewDetail.set('Uid',userid);
                        var array = new Array();
                        array.push(date.Day);
                        addNewDetail.set('M'+(date.Month),array);
                        addNewDetail.set('Year',parseInt(date.Year));
                        //console.log('======updateDetail save start=====');
                        addNewDetail.save().then(function(){
                            //console.log('======updateDetail end1=====');
                            callback(null, {code:0});
                        }).catch(function(err){
                            callback({code:9993,reason:err});
                        });
                    }else{
                        var array = new Array();
                        //console.log('=================1:');
                        //console.log(detail.get('M'+(date.Month)));
                        if(typeof (detail.get('M'+(date.Month))) != 'undefined' && detail.get('M'+(date.Month)) != null){
                            array =  detail.get('M'+(date.Month));
                        }else{
                            array =  [];
                        }
                        //console.log('=================2:');
                        //console.log(array);
                        array.push(date.Day);
                        detail.set('M'+(date.Month),array);
                        detail.set('Year',parseInt(date.Year));
                        detail.save().then(function(){
                            //console.log('======updateDetail end2=====');
                            callback(null, {code:0,msg:'updateDetail success'});
                        }).catch(function(err){
                            callback({code:9993,reason:err});
                        });
                    }
                }],
                //查询出最新的User表中的数据（月累计天数和总的累计天数）
                /*hasGift:['updateDetail',function(callback,results){
                 var query = new AV.Query(SignDayUserM);
                 query.equalTo('Uid',userid);
                 query.first().then(function(giftInfo){
                 console.log('======hasGift=====');
                 callback(null, giftInfo);
                 }).catch(function(err){
                 callback(err);
                 });
                 }],*/
                /*check:function(callback,results){
                 console.log('======check=====');
                 callback(null, {code:1,msg:'1111'});
                 }*/
                //查询出最新的User表中的数据（月累计天数和总的累计天数）
                checkGift:['updateDetail','getGiftRule','updateUser',function(callback,results){

                    //console.log('======checkGift=====');
                    var monthSignDay = results.updateUser.MonthSignDay;
                    var allSignDay = results.updateUser.AllSignDay;
                    var lastTimeYear = results.updateUser.Year;
                    var lastTimeMonth = results.updateUser.Month;
                    var lastTimeDay = results.updateUser.Day;
                    var currentMonthDays = new Date(new Date().getFullYear(),(new Date().getMonth()+1),0).getDate();
                    //console.log("当月的天数："+currentMonthDays);
                    var days = [3,15,currentMonthDays] ;
                    var allsign = [90,180,365];
                    if((days.indexOf(monthSignDay)==-1 && allsign.indexOf(allSignDay)==-1)){
                        //console.log(days.indexOf(monthSignDay)==-1 || allsign.indexOf(allSignDay)==-1);
                        //console.log('当前不满足'+'monthSignDay:'+monthSignDay+'allSignDay:'+allSignDay);
                        return callback(null, {code:0,msg:'success'});
                    }
                    var query = new SignDayGiveM();
                    query.set('Uid',userid);
                    query.set('Year',lastTimeYear);
                    query.set('Month',lastTimeMonth);
                    if( monthSignDay === 3){
                        //3天送积分
                        query.set('Mold','0');
                        query.set('RuleDays','D3');
                        query.set('GiveGift',0);
                    }
                    if( monthSignDay === 15){
                        //15天送优惠卷
                        query.set('Mold','0');
                        query.set('RuleDays','D15');
                        query.set('GiveGift',1);
                        query.set('GiveRule',results.getGiftRule['15'].id);
                    }
                    if(monthSignDay === new Date(lastTimeYear,lastTimeMonth,0).getDate()){
                        //一个月送水果（此一个月为自然月，不一定是30天）
                        query.set('Mold','0');
                        query.set('RuleDays','D30');
                        query.set('GiveGift',0);
                    }
                    if(allSignDay === 90){
                        //90天送。。。
                        query.set('Mold','0');
                        query.set('RuleDays','D90');
                        query.set('GiveGift',1);
                        query.set('AllSignEnable',true);
                        query.set('GiveRule',results.getGiftRule['90'].id);
                    }
                    if(allSignDay === 180){
                        //180天送。。。
                        query.set('Mold','0');
                        query.set('RuleDays','D180');
                        query.set('GiveGift',1);
                        query.set('AllSignEnable',true);
                    }
                    if(allSignDay === 365){
                        //365天送。。。
                        query.set('Mold','0');
                        query.set('RuleDays','D365');
                        query.set('GiveGift',0);
                        query.set('AllSignEnable',true);
                    }
                    //是否可以领取
                    query.set('GiveMold',0);
                    query.save().then(function(){
                        callback(null, {code:0,msg:'success'});
                    }).catch(function(err){
                        callback({code:9992,reason:err});
                    });
                }],
                finalFunction:['checkGift',function(callback,results){
                    callback(null, {code:0,msg:'Good && Success',updateUser:results.updateUser});
                }]
            },function(err,results){
                if(err){
                    promise.reject(err);
                }else{
                    promise.resolve(results.finalFunction);
                }
            });
            return promise;
        }else{
            return new AV.Promise.error("userid should not be empty!");
        }
    },
    /**
     * 签到操作2-判断签到天数生成待领取记录(Molde内部调用)	Myron	addSginDayGiftGive
     * !userid:String,!Year:Int,!month:Int，!Mold:Int!RuleDays:Int,!GiveRuleID:Int
     * code:int,msg:string
     * @param userid
     * @param Year
     * @param month
     * @param Mold
     * @param RuleDays
     * @param GiveRuleID
     */
    addSignDayGiftGive:function(){
        var promise = new AV.Promise();
        var days = [3,15,30];
        promise.resolve(days.indexOf(40));
        return promise;
    },
    //获取签到礼品记录
    getSingDayGiftArray:function(userid,year,month){
        var promise = new AV.Promise();
        var result = new Array();
        var obj = {};
        if (userid && year && month){
            async.waterfall([
                function(callback){
                    var query = new AV.Query(ActivitySignDayGive);
                    query.equalTo('Uid',userid);
                    query.equalTo('Year',year);
                    query.equalTo('Month',month);
                    query.equalTo('RuleDays','D3');
                    var objD3 = {};
                    query.first().then(function(res){
                        if(res){
                            objD3['D3ObjectId'] = res.id;
                            objD3['D3Value'] = res.get('GiveMold');
                            result.push(objD3);
                            callback(null,result);
                        }else{
                            objD3['D3ObjectId'] = "";
                            objD3['D3Value'] = -1;
                            result.push(objD3);
                            callback(null,result);
                        }
                    }).catch(function(err){
                        callback(err);
                    });
                },
                function(result,callback){
                    var query = new AV.Query(ActivitySignDayGive);
                    query.equalTo('Uid',userid);
                    query.equalTo('Year',year);
                    query.equalTo('Month',month);
                    query.equalTo('RuleDays','D15');
                    var objD15 = {};
                    query.first().then(function(res){
                        if(res){
                            objD15['D15ObjectId'] = res.id;
                            objD15['D15Value'] = res.get('GiveMold');
                            result.push(objD15);
                            callback(null,result);
                        }else{
                            objD15['D15ObjectId'] = "";
                            objD15['D15Value'] = -1;
                            result.push(objD15);
                            callback(null,result);
                        }
                    }).catch(function(err){
                        callback(err);
                    });
                },
                function(result,callback){
                    var query = new AV.Query(ActivitySignDayGive);
                    query.equalTo('Uid',userid);
                    query.equalTo('Year',year);
                    query.equalTo('Month',month);
                    query.equalTo('RuleDays','D30');
                    var objD30 = {};
                    query.first().then(function(res){
                        if(res){
                            objD30['D30ObjectId'] = res.id;
                            objD30['D30Value'] = res.get('GiveMold');
                            result.push(objD30);
                            callback(null,result);
                        }else{
                            objD30['D30ObjectId'] = "";
                            objD30['D30Value'] = -1;
                            result.push(objD30);
                            callback(null,result);
                        }
                    }).catch(function(err){
                        callback(err);
                    });
                },
                function(result,callback){
                    var query = new AV.Query(ActivitySignDayGive);
                    query.equalTo('Uid',userid);
                    query.equalTo('RuleDays','D90');
                    query.equalTo('AllSignEnable',true);
                    var objD90 = {};
                    query.first().then(function(res){
                        if(res){
                            objD90['D90ObjectId'] = res.id;
                            objD90['D90Value'] = res.get('GiveMold');
                            result.push(objD90);
                            callback(null,result);
                        }else{
                            objD90['D90ObjectId'] = "";
                            objD90['D90Value'] = -1;
                            result.push(objD90);
                            callback(null,result);
                        }
                    }).catch(function(err){
                        callback(err);
                    });
                },
                function(result,callback){
                    var query = new AV.Query(ActivitySignDayGive);
                    query.equalTo('Uid',userid);
                    query.equalTo('RuleDays','D180');
                    query.equalTo('AllSignEnable',true);
                    var objD180 = {};
                    query.first().then(function(res){
                        if(res){
                            objD180['D180ObjectId'] = res.id;
                            objD180['D180Value'] = res.get('GiveMold');
                            result.push(objD180);
                            callback(null,result);
                        }else{
                            objD180['D180ObjectId'] = "";
                            objD180['D180Value'] = -1;
                            result.push(objD180);
                            callback(null,result);
                        }
                    }).catch(function(err){
                        callback(err);
                    });
                },
                function(result,callback){
                    var query = new AV.Query(ActivitySignDayGive);
                    query.equalTo('Uid',userid);
                    query.equalTo('RuleDays','D365');
                    query.equalTo('AllSignEnable',true);
                    var objD365 = {};
                    query.first().then(function(res){
                        if(res){
                            objD365['D365ObjectId'] = res.id;
                            objD365['D365Value'] = res.get('GiveMold');
                            result.push(objD365);
                            callback(null,result);
                        }else{
                            objD365['D365ObjectId'] = "";
                            objD365['D365Value'] = -1;
                            result.push(objD365);
                            callback(null,result);
                        }
                    }).catch(function(err){
                        callback(err);
                    });
                },
            ],function(err,result){
                if(err){
                    promise.reject(err);
                }else{
                    obj['code'] = 0;
                    obj['GiftArray'] = result;
                    promise.resolve(obj);
                }
            });
            return promise;
        }else{
            return new AV.Promise.error('params should not be empty!');
        }
    },
    //获取日历中的签到天数数据
    getSignDayDetail:function(userid,month){
        var promise = new AV.Promise();
        var query = new AV.Query(ActivitySignDayDetail);
        var recod;
        var obj = {};
        obj['code'] = 0
        var date=new Date;
        var year=date.getFullYear();

        query.equalTo('Uid',userid);
        query.equalTo('Year',year);
        query.first().then(function(result){
            if(result){
                var m = "M"+month;
                recod = result.get(m);
                if(recod){
                    obj['data'] = recod;
                }else{
                    obj['data'] = [];
                }
                promise.resolve(obj);
            }else{
                obj['data'] = [];
                promise.resolve(obj);
            }
        }).catch(function(err){
            obj['data'] = [];
            promise.resolve(obj);
        });
        return promise;
    },
    //实物礼品领取,实物加入购物车
    setSignDayGiftCart:function(userid,GiftGiveID){
        var promise = new AV.Promise();

        if(userid && GiftGiveID){
            async.waterfall([
                //1.判断是否有未领取的奖品记录
                function(callback){
                    var query = new AV.Query(ActivitySignDayGive);
                    query.equalTo('Uid',userid);
                    query.equalTo('objectId',GiftGiveID);
                    query.equalTo('GiveMold',0);
                    query.first().then(function(res){
                        if(res){
                            callback(null,res);
                        }else{
                            promise.resolve({code:-1,msg:'不存在该奖品领取记录或改奖品已被领取'});
                        }
                    }).catch(function(err){
                        callback(err);
                    });
                },
                //2.如果有可以领取的记录，找到该奖品，并加入到购物车中，model为3表示签到送的
                function(res,callback){
                    var query = new AV.Query('ActivitySignDayRule');
                    query.get(res.get('GiveRule')).then(function(resDayRule){
                        if(resDayRule){
                            cartCtrl.insertProToCart(resDayRule.get('PID'),resDayRule.get('PSID'),1,userid,'3').then(function(resCart){
                                callback(null,res);
                            }).catch(function(err){
                                promise.resolve({code:-3,msg:'签到礼品加入购物车失败'});
                            })
                        }else{
                            promise.resolve({code:-2,msg:'不存在该奖品'});
                        }
                    }).catch(function(err){
                        callback(err);
                    });
                },
                //3.加入购物车后，将该奖品领取记录设置为已领取
                function(res,callback){
                    res.set('GiveMold',1);
                    res.set('GiveTime',new Date());
                    res.save().then(function(post) {
                        callback(null);
                    }).catch(function(err){
                        callback(err);
                    })
                }
            ],function(err,result){
                if(err){
                    promise.reject(err);
                }else{
                    promise.resolve({code:0,msg:"已成功领取签到礼物"});
                }
            });
            return promise;
        }else{
            return new AV.Promise.error('userid or GiftGiveID should not be empty');
        }
    },
};
